/**
 * API 路由
 *
 * @author bian
 * @createDate 2016.4.24
 */
var path = require("path");
var fs = require("fs");

var db = require("../models/index");
var auth = require("../instances/auth");
var msgWrapper = require("../helpers/msgWrapper");
var DataAdaptor = require("../modelAdaptor/Data");

var Data = db.models.Data;

module.exports = (router) => {
    
    var prefix = (url) => {
        var re = /\/token\/.*/gi, new_url = `/token${url}`;
        if(! re.test(new_url)) throw 'url write error';
        return new_url;
    };

    /**
     * 得到当前连接的设备列表
     */
    router.all(prefix("/getConnectList"),function(req,res){
        var user = auth.user(req);
        if(user && user.type !== 1) {
            res.send(msgWrapper('you are not adminer'),true);
            return;
        }
        var app = req.app;
        var socketsName = app.locals.sockets;
        var ids = [];
        for(var x in socketsName){
            ids.push(socketsName[x].name);
        }
        res.send(msgWrapper({
            list:ids
        }));
    });

    /**
     * 老接口不动
     */
    router.all(prefix("/getTemperature"),function(req,res){
        Data.findAll({          // 一次返回20个
            where:{
                equipment : "intelSenor",
                type : "temperature",
            },
            order : [["createdAt","DESC"]],
            limit : 20
        }).then(function(data){
            res.send(msgWrapper({
                list : data
            }));
        });
    });

    /**
     * switch and lantern写在一起，修改起来方便
     *
     * @modify 老接口不动
     */
    router.all(prefix("/:equipment/:action"),function(req,res){
        req.checkParams('equipment').notEmpty();
        req.checkParams('action').notEmpty();
        if(req.errors){
            res.send(msgWrapper('equipment or action empty in url',true));
            return;
        }
        var equipment = req.params.equipment;
        switch (equipment) {
            case 'switch' :
                equipment = 'switch';break;
            case 'lantern' :
                equipment = 'lantern';break;
            default :
                equipment = 'switch';
        }
        var action = req.params.action === 'on';
        var socket,
            sockets = req.app.locals.sockets;
        //todo : 改成多用户
        for(var i in sockets){
            socket = sockets[i].name === "Intel" ? sockets[i] : null;
        }
        if(! socket){
            res.send(msgWrapper('device is not connect network',true));
            return;
        }
        socket.emit(equipment,{
            action : action
        });
        res.send(msgWrapper('ok'));
    });

    router.all("/clear",function (req,res){
        Data.destroy({
            where:{

            }
        }).then(function(){
            res.send(msgWrapper({
                action : "del"
            }));
        });
    });
};